"""
General utility functions.
"""

import pandas as pd
from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem
from PyQt5 import QtGui

from .setting import SETTINGS
import pts.global_variable as glv


def getAmountFromValue(va: float) -> str:
    s = ''
    if not va:
        return s

    if type(va) == type('str'):
        try:
            va = float(va)
        except BaseException as ex:
            # print(ex.args)
            # print(va)
            return va

    if va > 100000000 or va < -100000000:
        va = va / 100000000
        s = "{:.2f}亿".format(va)
    elif va > 10000 or va < -10000:
        va = va / 10000
        s = "{:.2f}万".format(va)
    else:
        s = str(va)

    return s


# bkKind：板块各类，0-无类型，1-行业板块，2-概念板块
# simuList：在不同地方同时出现的板块，需要强调，用黄色背景显示
# amountList：金额列，需要根据值转换为万、亿等表示法
# decimalList：小数列，需要控制小数点后的位数
# startCol：从第几列开始显示（跳过前面的索引列）
# orderCol：排序字段，灰色背景，文字根据正负红绿
def displayDataFrame(df: pd.DataFrame, tw: QTableWidget, bkKind: int = 0, simuList: list = [], amountList: list = [], decimalList: list = [], startCol: int = 0,
                     nameCol: int = 1, orderCol: list = []):
    headers = df.columns[startCol:]
    cnum = len(headers)
    tw.setColumnCount(cnum)
    tw.setHorizontalHeaderLabels(headers)
    tw.setRowCount(len(df))
    for index, row in df.iterrows():
        name = row[nameCol]
        flag1 = False
        if index < SETTINGS["block.number"] and name in simuList:
            flag1 = True
        # 是否属于固定板块
        flag2 = False
        if (bkKind == 1 and name in glv.gHYBlockGD) or (bkKind == 2 and name in glv.gGNBlockGD):
            flag2 = True
        # 是否属于排除板块
        flag3 = False
        if (bkKind == 1 and name in glv.gHYBlockPC) or (bkKind == 2 and name in glv.gGNBlockPC):
            flag3 = True
        for i in range(startCol, len(row)):
            # 取原始字符串
            istr = str(row[i])
            if i in amountList:
                # 如果是金额列
                istr = getAmountFromValue(row[i])
            elif i in decimalList:
                # 如果是小数列
                istr = '{:.4f}'.format(row[i])
            item = QTableWidgetItem(istr)
            if flag2:
                item.setForeground(QtGui.QColor(255, 0, 0))
            if flag3:
                item.setForeground(QtGui.QColor(0, 155, 0))
            # 如果是排序字段
            if i in orderCol:
                item.setBackground(QtGui.QColor(222, 222, 222))
                try:
                    va = float(row[i])
                    if va > 0:
                        item.setForeground(QtGui.QColor(255, 0, 0))
                    else:
                        item.setForeground(QtGui.QColor(0, 155, 0))
                except BaseException as ex:
                    pass
            if flag1:
                item.setBackground(QtGui.QColor(252, 222, 156))
            tw.setItem(index, i - startCol, item)


def displayDataFrame1(df: pd.DataFrame, tw: QTableWidget, amount: list = []):
    headers = df.columns[1:]
    cnum = len(headers)
    tw.setColumnCount(cnum)
    tw.setHorizontalHeaderLabels(headers)
    tw.setRowCount(len(df))
    for index, row in df.iterrows():
        for i in range(1, len(row)):
            istr = str(row[i])
            if i in amount:
                istr = getAmountFromValue(row[i])
            item = QTableWidgetItem(istr)
            tw.setItem(index, i - 1, item)

# bk：板块各类，1-行业板块，2-概念板块
def displayDataFrame2(bk: int, df: pd.DataFrame, tw: QTableWidget, ser: list, amount: list = []):
    headers = df.columns[1:]
    cnum = len(headers)
    tw.setColumnCount(cnum)
    tw.setHorizontalHeaderLabels(headers)
    tw.setRowCount(len(df))
    for index, row in df.iterrows():
        name = row[1]
        flag1 = False
        if index < SETTINGS["block.number"] and name in ser:
            flag1 = True
        flag2 = False
        if (bk == 1 and name in glv.gHYBlockGD) or (bk == 2 and name in glv.gGNBlockGD):
            flag2 = True
        flag3 = False
        if (bk == 1 and name in glv.gHYBlockPC) or (bk == 2 and name in glv.gGNBlockPC):
            flag3 = True
        for i in range(1, len(row)):
            istr = str(row[i])
            if i in amount:
                istr = getAmountFromValue(row[i])
            item = QTableWidgetItem(istr)
            if flag1:
                item.setBackground(QtGui.QColor(252, 222, 156))
            if flag2:
                item.setForeground(QtGui.QColor(255, 0, 0))
            if flag3:
                item.setForeground(QtGui.QColor(0, 155, 0))
            tw.setItem(index, i - 1, item)
